<template>
	<div>
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item :to="{ path: '/merchants' }" >商城管理</el-breadcrumb-item>
			<el-breadcrumb-item :to="{ path: '/merchants' }" >商户管理</el-breadcrumb-item>
			<el-breadcrumb-item :to="{ path: '/addMerchant' }" >选择品牌</el-breadcrumb-item>
			<el-breadcrumb-item>编辑商户</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card>
			<el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit">
			  <el-tab-pane
				:key="index"
				v-for="(item, index) in editableTabs"
				:label="item.shopName"
				:name="String(index)"
			  >
				  <p>基本信息</p>
				  <el-divider></el-divider>
				  <el-row :gutter="60">
					<el-col :span="12">
						<span>序号</span>
						<el-input v-model="item.sort"></el-input>
					</el-col>
					<el-col :span="12">
						<span>商户名称</span>
						<el-input v-model="item.shopName"></el-input>
					</el-col>
					<el-col :span="12">
						<span>品类</span>
						<el-select v-model="item.menuId" placeholder="选择分类">
							<el-option value="" label="请选择分类"></el-option>
							<el-option
							  v-for="itemo in options1"
							  :key="itemo.menuId"
							  :label="itemo.name"
							  :value="itemo.menuId">
							</el-option>
						  </el-select>
					</el-col>
					<el-col :span="12">
						<span>所在地</span>
						<el-select v-model="item.city" placeholder="选择所在地">
							<el-option value="" label="选择所在地"></el-option>
							<el-option value="南京市" label="南京市"></el-option>
							<el-option value="苏州市" label="苏州市"></el-option>
							<el-option value="无锡市" label="无锡市"></el-option>
						</el-select>
					</el-col>
					<el-col :span="12">
						<span>联系方式</span>
						<el-input v-model="item.shopPhone"></el-input>
					</el-col>
					<el-col :span="12">
						<span>地址</span>
						<el-input v-model="item.shopAddress"></el-input>
					</el-col>
					<el-col :span="12">
						<div>
							<span>logo</span>
							<el-button type="primary" size="mini" @click="chooseImage()">点击上传</el-button>
							<input @change="photoChange($event)" type="file" :id="'upload_file'+index" multiple style="display: none"/>
						</div>
						<div v-if="item.orderImage != ''" style="margin-left: 10px;">
							<img class="editIcon" :src="'data:image/jpeg;base64,'+item.orderImage" />
						</div>
					</el-col>
					<el-col :span="12">
						<span>月销量</span>
						<el-input v-model="item.sellCounts"></el-input>
					</el-col>
				  </el-row>
				  <p>详细信息</p>
				  <el-divider></el-divider>
				  <el-row :gutter="60">
					<el-col :span="24"  style="display: block;">
						<span>商户头图</span>
						<el-button type="primary" size="mini" @click="choosefirstImage()">点击上传</el-button>
						<input @change="photofirstChange($event)" type="file" :id="'upload_file_first'+index" multiple style="display: none"/>
						<div class="imgList">
							<div class="imgItem" v-for="(itemf,indexf) in item.firstImgList">
								<div class="img-wapper-top-clear"  @click="deleteImg(1,index,indexf)"><img src="https://acetech.oss-cn-beijing.aliyuncs.com/aceTechAdminWeb/deleteimg.png"></div>
								<img class="imgItem-con" :src="'data:image/jpeg;base64,'+itemf.firstUrl" alt="">
							</div>
						</div>
					</el-col>
					<el-col :span="12">
						<span>营业时间</span>
						<el-input v-model="item.shopHours"></el-input>
					</el-col>
					<el-col :span="12">
						<span>开业时间</span>
						<el-input v-model="item.shopOpenHours"></el-input>
					</el-col>
					<el-col :span="12">
						<span>门店面积</span>
						<el-input v-model="item.shopStoreArea"></el-input>
					</el-col>
					<el-col :span="12">
						<span>其他设施</span>
						<el-input v-model="item.shopFacilities"></el-input>
					</el-col>
					<el-col :span="24" style="display: block;">
						<span>商户介绍图</span>
						<el-button type="primary" size="mini" @click="choosesecondImage()">点击上传</el-button>
						<input @change="photosecondChange($event)" type="file" :id="'upload_file_second'+index" multiple style="display: none"/>
						<div class="imgList">
							<div class="imgItem" v-for="(items,indexs) in item.secondImgList">
								<div class="img-wapper-top-clear" @click="deleteImg(2,index,indexs)"><img src="https://acetech.oss-cn-beijing.aliyuncs.com/aceTechAdminWeb/deleteimg.png"></div>
								<img class="imgItem-con" :src="'data:image/jpeg;base64,'+items.secondUrl" alt="">
							</div>
						</div>
					</el-col>
					<el-col :span="12">
						<span>保存后立即开启</span>
						<el-radio-group v-model="item.onOffStatus">
							<el-radio :label="1">立即开启</el-radio>
							<el-radio :label="2">暂不开启</el-radio>
						  </el-radio-group>
					</el-col>
				  </el-row>
				  <p>商品管理</p>
				  <el-divider></el-divider>
				  <el-button type="primary" @click="seachEquery('','2','isadd')">添加</el-button>
				  <el-table :data="item.itemsInfoList" border stripe>
					<el-table-column prop="sort" label="商品序号"></el-table-column>
					<el-table-column prop="itemName" label="商品名称"></el-table-column>
					<el-table-column prop="priceNormal" label="价格"></el-table-column>
					<el-table-column prop="reserveCounts" label="库存"></el-table-column>
					<el-table-column label="属性">
						<template slot-scope="scope">
							{{scope.row.itemType == 'all'?'品牌通用':'仅本店'}}
						</template>
					</el-table-column>
					<el-table-column label="状态">
						<template slot-scope="scope">
							<el-switch
							    v-model="scope.row.onOffStatus"
								@change="statusChanged(scope.row,scope.row.itemId)"
							    active-color="#13ce66"
							    inactive-color="#ff4949"
							    active-value="1"
							    inactive-value="0">
							</el-switch>
						</template>
					</el-table-column>
					<el-table-column label="操作">
						<template slot-scope="scope">
							<el-button size="mini" type="primary" @click="seachEquery(scope.row.itemId,'1')">查看</el-button>
							<el-button size="mini" type="primary" @click="seachEquery(scope.row.itemId,'2')">编辑</el-button>
						</template>
					</el-table-column>
				  </el-table>
				  <el-button type="primary" @click="saveInfo">保存</el-button>
				  <el-button @click="back">取消</el-button>
			  </el-tab-pane>
			</el-tabs>
		</el-card>
		
		<el-dialog
		  :title="isAddInfo?'添加':'修改'"
		  :visible.sync="editDialogVisible"
		  width="80%">
			<el-row :gutter="60">
				<el-col :span="12">
					<span>商品序号</span>
					<el-input v-model="editinfoList.sort" :disabled="disabledType" placeholder="0~99，数字越大排序越靠前"></el-input>
				</el-col>
				<el-col :span="12">
					<span>商品名称</span>
					<el-input v-model="editinfoList.itemName" :disabled="disabledType" placeholder="输入商品名称"></el-input>
				</el-col>
				<el-col :span="12">
					<span>售价</span>
					<el-input v-model="editinfoList.priceDiscount" :disabled="disabledType" placeholder="输入实际价格,例:100元"></el-input>
				</el-col>
				<el-col :span="12">
					<span>原价</span>
					<el-input v-model="editinfoList.priceNormal" :disabled="disabledType" placeholder="输入商品原价,例:100元"></el-input>
				</el-col>
				<el-col :span="12">
					<span>生效时间</span>
					<el-date-picker
					  v-model="editinfoList.startTime"
					  type="datetime"
					  value-format="yyyy-MM-dd HH:mm:ss"
					  placeholder="生效时间">
					</el-date-picker>
				</el-col>
				<el-col :span="12">
					<span>有效期</span>
					<el-input v-model="editinfoList.validityCount" :disabled="disabledType" placeholder="输入有效天数,例:100天"></el-input>
				</el-col>
				<el-col :span="12">
					<span>次数</span>
					<el-input v-model="editinfoList.counts" :disabled="disabledType" placeholder="输入商品使用次数"></el-input>
				</el-col>
				<el-col :span="24" class="listWapper">
					<span>营销标签</span>
					<div class="listInner-out">
						<div v-for="(item,index) in editinfoList.tagVoList" class="listInner">
							<el-input v-model="item.value" :disabled="disabledType" placeholder="输入标签内容"></el-input>
							<el-input v-model="item.code" :disabled="disabledType" placeholder="输入标签色值"></el-input>
							<span class="tips">非必填</span>
						</div>
					</div>
				</el-col>
				<el-col :span="24" class="listWapper">
					<span>商品介绍</span>
					<div class="listInner-out">
						<div v-for="(item,index) in editinfoList.content" class="listInner">
							<el-input v-model="item.title" :disabled="disabledType" placeholder="输入介绍标题"></el-input>
							<el-input v-model="item.details" :disabled="disabledType" placeholder="输入介绍内容"></el-input>
							<el-input v-model="item.counts" :disabled="disabledType" placeholder="输入介绍备注"></el-input>
							<div class="add" @click="addContent(index)" v-if="!disabledType">添加</div>
							<div class="del" @click="deleteList('content',index)" v-if="!disabledType && editinfoList.content.length>1">删除</div>
						</div>
					</div>
				</el-col>
				<el-col :span="24" class="listWapper">
					<span>购买须知</span>
					<div class="listInner-out">
						<div v-for="(item,index) in editinfoList.sellRemark" class="listInner">
							<el-input v-model="item.title" :disabled="disabledType" placeholder="输入须知标题"></el-input>
							<el-input v-model="item.content" :disabled="disabledType" placeholder="输入须知内容"></el-input>
							<div class="add"  @click="addSellRemark(index)" v-if="!disabledType">添加</div>
							<div class="del" @click="deleteList('sellRemark',index)" v-if="!disabledType && editinfoList.sellRemark.length>1">删除</div>
						</div>
					</div>
				</el-col>
				<el-col :span="24" class="listWapper">
					<span>使用规则</span>
					<div class="listInner-out">
						<div v-for="(item,index) in editinfoList.remark" class="listInner">
							<el-input v-model="item.content" :disabled="disabledType" placeholder="输入规则内容"></el-input>
							<div class="add" @click="addRemark(index)" v-if="!disabledType">添加</div>
							<div class="del"  @click="deleteList('remark',index)" v-if="!disabledType && editinfoList.remark.length>1">删除</div>
						</div>
					</div>
				</el-col>
				<el-col :span="12">
					<span>商品库存</span>
					<el-input v-model="editinfoList.reserveCounts" :disabled="disabledType" placeholder="商品库存"></el-input>
				</el-col>
				<el-col :span="12">
					<span>商品属性</span>
					<el-select v-model="editinfoList.itemType" placeholder="请选择" :disabled="disabledType">
						<el-option value="" label="请选择"></el-option>
						<el-option value="all" label="品牌通用"></el-option>
						<el-option value="common" label="仅本店"></el-option>
					</el-select>
				</el-col>
				<el-col :span="12">
					<span>保存上架</span>
					<el-radio v-model="editinfoList.onOffStatus" :label="1">立即上架</el-radio>
					<el-radio v-model="editinfoList.onOffStatus" :label="2">暂不上架</el-radio>
				</el-col>
			</el-row>
			<el-button type="primary" v-if="!disabledType" @click="editinfoSave">保存</el-button>
			<el-button @click="editDialogVisible = false">取消</el-button>
		</el-dialog>
		
	</div>
</template>

<script>
	var that
  export default {
    data() {
      return {
        editableTabsValue: '0',
        editableTabs: [],
        tabIndex:2,
		modulelist:{
			"brandId":this.$route.query.id,
			"sort":"",
			"shopName":"新增",
			"menuId":"",
			"city":"",
			"shopAddress":"",
			"shopPhone":"",
			"shopOpenHours":"",
			"orderImage":"",
			"shopHours":"",
			"shopStoreArea":"",
			"shopFacilities":"",
			"onOffStatus":1,
			"isAdd":true,
			"firstImgList":[
			],
			"secondImgList":[
			]
		},
		options1:[],
		editinfoList:[],
		editDialogVisible:false,
		disabledType:false,
		tagVoList:{"tagId":"","code":"","value":""},/* 营销标签 */
		content:{"title":"","details":"","counts":""},/* 商品介绍 */
		sellRemark:{"title":"","content":""},/* 购买须知 */
		remark:{"content":""},/* 使用规则 */
		isAddInfo:false
      }
    },
	created() {
		this.getInfo()
		this.getCategory()
		that = this
	},
    methods:{
		async getInfo(){
			const loading = this.$loading({
			  lock: true,
			  text: 'Loading',
			  spinner: 'el-icon-loading',
			  background: 'rgba(0, 0, 0, 0.7)'
			});
			const {data:res} = await this.$http.post('/brand/queryDetailsByBrandId',{id:this.$route.query.id})
			loading.close();
			if(res.data.length == 0){
				this.editableTabs.push(this.modulelist)
			}else{
				res.data.forEach(async (item,index) => {
					this.$set(item,'isAdd',false);
					this.$set(item,'onOffStatus',item.shopOnOffStatus);
					
					var orderImage = ''
					await this.$base64Img(item.orderImage).then((res) => {		//调用全局方法
						orderImage = res
					})
					item.orderImage = orderImage.split(',')[1]
					
					item.firstImgList.forEach(async (itemfi,indexfi) => {
						var firstUrl = ''
						await this.$base64Img(itemfi.firstUrl).then((res) => {		//调用全局方法
							firstUrl = res
						})
						itemfi.firstUrl = firstUrl.split(',')[1]
					})
					
					item.secondImgList.forEach(async (itemse,indexse) => {
						var secondUrl = ''
						await this.$base64Img(itemse.secondUrl).then((res) => {		//调用全局方法
							secondUrl = res
						})
						itemse.secondUrl = secondUrl.split(',')[1]
					})
				})
				this.editableTabs = res.data
			}
			
		},
		async getCategory(){
			const {data:res} = await this.$http.get('/shopManage/menuList')
			this.options1 = res.data
		},
		handleTabsEdit(targetName, action) {
			if (action === 'add') {
			  this.editableTabs.push(this.modulelist);
			  this.editableTabsValue = String(this.editableTabs.length-1) ;
			}
		},
		chooseImage(){
			document.getElementById('upload_file'+this.editableTabsValue).click(); //触发input-file文件上传控件 事件photoChange
　　　　},
		async photoChange(el) {
			var file = el.target.files[0];//name: "dangqi1.png" || type: "image/png"
			var type = file.type.split('/')[0];
			if ( type === 'image' ){
				var dataURL = await this.toBase64(file)
				this.editableTabs[this.editableTabsValue].orderImage = dataURL.split(',')[1]
			}else{
				alert('上传了非图片');
			}
		},
		choosefirstImage(){
			document.getElementById('upload_file_first'+this.editableTabsValue).click(); //触发input-file文件上传控件 事件photoChange
　　　　　　},
		async photofirstChange(el) {
			var file = el.target.files[0];//name: "dangqi1.png" || type: "image/png"
			var type = file.type.split('/')[0];
			if ( type === 'image' ){
				var dataURL = await this.toBase64(file)
				this.editableTabs[this.editableTabsValue].firstImgList.push({"firstId":'',"firstUrl":dataURL.split(',')[1]})
			}else{
				alert('上传了非图片');
			}
		},
		choosesecondImage(){
			document.getElementById('upload_file_second'+this.editableTabsValue).click(); //触发input-file文件上传控件 事件photoChange
　　　　　　},
		async photosecondChange(el) {
			var file = el.target.files[0];//name: "dangqi1.png" || type: "image/png"
			var type = file.type.split('/')[0];
			if ( type === 'image' ){
				var dataURL = await this.toBase64(file)
				this.editableTabs[this.editableTabsValue].secondImgList.push({"secondId":'',"secondUrl":dataURL.split(',')[1]})
			}else{
				alert('上传了非图片');
			}
		},
		toBase64(file){
			return new Promise(function(resolve, reject) { 
				//将图片img转化为base64
				var reader = new FileReader();
				reader.readAsDataURL(file);
				reader.onloadend = function () {
					resolve(reader.result)
				};
			})
		},
		deleteImg(e,index,indexfs){/* 删除数组图片 */
			if(e==1){
				this.editableTabs[index].firstImgList.splice(indexfs,1)
			}else{
				this.editableTabs[index].secondImgList.splice(indexfs,1)
			}
		},
		async saveInfo(){
			const loading = this.$loading({
			  lock: true,
			  text: 'Loading',
			  spinner: 'el-icon-loading',
			  background: 'rgba(0, 0, 0, 0.7)'
			});
			var merchant = {"saveShopList":[],"updateShopList":[]}
			this.editableTabs.forEach((item,index) => {
				if(item.isAdd){/* 为新增 */
					merchant["saveShopList"].push(item)
				}else{/* 为修改 */
					merchant["updateShopList"].push(item)
				}
			})
			const {data:res} = await this.$http.post('/shopManage/saveAndUpdate',merchant)
			loading.close();
			if(res.code!==200) {
				return this.$message.error('修改失败')
			}
			this.$message.success('修改成功')
			this.$router.push({path:"/addMerchant"})
		},
		back(){
			this.$router.push({path:"/addMerchant"})
		},
		async seachEquery(id,num,isadd){
			if(num == 1){
				this.disabledType = true
			}else{
				this.disabledType = false
			}
			if(isadd == 'isadd'){
				this.editinfoList={
					"itemId":"",
					"sort":"",
					"itemName":"",
					"priceDiscount":"",
					"priceNormal":"",
					"startTime":"",
					"endTime":"",
					"counts":0,
					"content":[{"title":"","details":"","counts":""}],
					"sellRemark":[{"title":"","content":""}],
					"remark":[{"content":""}],
					"reserveCounts":0,
					"itemType":"common",
					"onOffStatus":1,
					"tagVoList":[{"tagId":"","code":"","value":""}]
				}
				this.isAddInfo = true
			}else{
				const loading = this.$loading({
				  lock: true,
				  text: 'Loading',
				  spinner: 'el-icon-loading',
				  background: 'rgba(0, 0, 0, 0.7)'
				});
				const {data:res} = await this.$http.post('/itemManage/queryItemsById',{id:id})
				loading.close();
				this.editinfoList = res.data
				if(this.editinfoList.tagVoList.length == 0 ){
					this.editinfoList.tagVoList=[{"tagId":"","code":"","value":""}]
				}
				this.editinfoList.content = JSON.parse(this.editinfoList.content)
				this.editinfoList.remark = JSON.parse(this.editinfoList.remark)
				this.editinfoList.sellRemark = JSON.parse(this.editinfoList.sellRemark)
				this.isAddInfo = false
			}
			this.editDialogVisible = true;
		},
		addContent(index){/* 添加商品介绍 */
			var that = this
			var content = []
			this.editinfoList.content.forEach((item,indexvv) => {
				content.push(item)
				if(index == indexvv){
					content.push(that.content)
				}
			})
			this.editinfoList.content = content
			this.content={"title":"","details":"","counts":""}
		},
		addSellRemark(index){
			var that = this
			var content = []
			this.editinfoList.sellRemark.forEach((item,indexvv) => {
				content.push(item)
				if(index == indexvv){
					content.push(that.sellRemark)
				}
			})
			this.editinfoList.sellRemark = content
			this.sellRemark={"title":"","content":""}
		},
		addRemark(index){
			var that = this
			var content = []
			this.editinfoList.remark.forEach((item,indexvv) => {
				content.push(item)
				if(index == indexvv){
					content.push(that.remark)
				}
			})
			this.editinfoList.remark = content
			this.remark={"content":""}
		},
		deleteList(e,index){
			this.editinfoList[e].splice(index,1)
		},
		async editinfoSave(){
			const loading = this.$loading({
			  lock: true,
			  text: 'Loading',
			  spinner: 'el-icon-loading',
			  background: 'rgba(0, 0, 0, 0.7)'
			});
			var remark =[];
			this.editinfoList.remark.forEach((item,index)=>{
				remark.push(item.content)
			})
			this.$set(this.editinfoList,'shopId',this.editableTabs[this.editableTabsValue].shopId);
			this.$set(this.editinfoList,'contentList',this.editinfoList.content);
			this.$set(this.editinfoList,'remarkList',remark);
			this.$set(this.editinfoList,'sellRemarkList',this.editinfoList.sellRemark);
			if(this.isAddInfo){
				const {data:res} = await this.$http.post('/itemManage/save',this.editinfoList)
				setTimeout(() => {
				  loading.close();
				}, 500);
				if(res.code!==200) {
					return this.$message.error('添加失败')
				}
				this.editDialogVisible = false;
				this.$message.success('添加成功')
				this.editableTabs[this.editableTabsValue].itemsInfoList.push(this.editinfoList)
			}else{
				const {data:res} = await this.$http.post('/itemManage/update',this.editinfoList)
				setTimeout(() => {
				  loading.close();
				}, 500);
				if(res.code!==200) {
					return this.$message.error('修改失败')
				}
				this.editDialogVisible = false;
				this.$message.success('修改成功')
				this.editableTabs[this.editableTabsValue].itemsInfoList.forEach((item,index) =>{
					if(item.itemId == this.editinfoList.itemId){
						this.editableTabs[this.editableTabsValue].itemsInfoList[index]=this.editinfoList
					}
				})
			}
		},
		// 监听switch状态改变
		async statusChanged(tableList,id){
			const loading = this.$loading({
			  lock: true,
			  text: 'Loading',
			  spinner: 'el-icon-loading',
			  background: 'rgba(0, 0, 0, 0.7)'
			});
			const {data:res} = await this.$http.post('/itemManage/updateType',{id:id,type:tableList.onOffStatus})
			loading.close();
			if(res.code!==200) {
				tableList.onOffStatus = !tableList.onOffStatus
				return this.$message.error('修改状态失败')
			}
		  this.$message.success('修改状态成功')
		},
    }
  }
</script>

<style lang="less" scoped>
	p{color: #1663af;font-weight: 600;}
	.el-col{
		display: flex;
		align-items: center;
		margin-bottom: 25px;
		span{
			display: inline-block;
			width: 80px;
			text-align: right;
			margin-right: 15px;
		}
		.el-input{
			width: 80%;
		}
	}
	.imgList{
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		margin-top: 15px;
		.imgItem{
			height: 90px;
			width: 160px;
			margin-right: 15px;
			border: 1px solid #c6c6c6;
			position: relative;
			.imgItem-con{
				height: 100%;
				width: 100%;
				position: absolute;
				z-index: 3;
			}
			.img-wapper-top-clear{
				width: 14px;
				height: 14px;
				position: absolute;
				z-index: 10;
				top: -7px;
				right: -7px;
				img{
					width: 100%;
					height: 100%;
				}
			}
		}
	}
	.el-table{
		margin-bottom: 25px;
	}
	.editIcon{
		width: 80px;
		height: 80px;
	}
	
	.listWapper{
		align-items: flex-start;
		flex-wrap: wrap;
		.listInner-out{
			flex: 1;
			.listInner{
				display: flex;
				align-items: center;
				justify-content: flex-start;
				margin-bottom: 15px;
				.el-input{
					margin-right: 20px;
					width: 28%;
				}
			}
			.listInner:last-child{
				margin-bottom:0;
			}
		}
	}
	.add{
		color: #007AFF;
		margin-left: 10px;
		cursor: pointer;
		font-size: 14px;
	}
	.del{
		color: #ff3c3f;
		margin-left: 10px;
		cursor: pointer;
		font-size: 14px;
	}
</style>
